#ifndef __UDP_SERVER_HPP__
#define __UDP_SERVER_HPP__

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <strings.h>
#include <functional>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

const static int gdefaultsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1"; //表示本地主机
const static uint16_t gdefaultport = 8080; // 1024以内的不行

using adduser_t = std::function<void(InetAddr &id)>;
using remove_t = std::function<void(InetAddr &id)>;
using task_t = std::function<void(std::string)>;
using route_t = std::function<void(int sockfd, const std::string &message)>;

using namespace LogModule;
using namespace ThreadPoolModule;

class nocopy
{
    public:
    nocopy(){}
    nocopy(const nocopy& a) = delete;
    const nocopy& operator = (const nocopy& a) = delete;
    ~nocopy(){}

};
class UdpServer : public nocopy    //这样服务器就不会被拷贝
{
public:
    UdpServer(uint16_t port = gdefaultport)
        : _sockfd(gdefaultsockfd),
          _addr(port),
          _isrunning(false)
    {
    }
    // 千篇一律
    void InitServer()
    {
        // 1.创建socket(文件信息)
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0); // 文件中的AF_INET
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            DIE(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is " << _sockfd;

        // 2.填充网络信息，并bind绑定
        // 还没有设置进入内核中
        //  struct sockaddr_in local;
        //  bzero(&local, sizeof(local)); //memset
        //  local.sin_family = AF_INET;
        //  local.sin_port = ::htons(_port); //要发送给对方，M 即要发到网络中,需要将主机序列转为网络字节序
        //  local.sin_addr.s_addr = ::inet_addr(_ip.c_str()); //字符串转成四字节，还要转成网络序列
        //  ocal.sin_addr.s_addr = INADDR_ANY; //全0

        // 设置进入内核中
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            DIE(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void RegisterService(adduser_t adduser, route_t route, remove_t removeuser)
    {
        _adduser = adduser;
        _route = route;
        _removeuser = removeuser;
    }
    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len);
            if (n > 0)
            {
                // 需要知道消息内容 && 消息发送者
                //  uint16_t clientport = ::ntohs(peer.sin_port);  //客户端的端口号
                //  std::string clientip = ::inet_ntoa(peer.sin_addr);  //客户端的IP地址

                InetAddr cli(peer);
                inbuffer[n] = 0;
                std::string message;
                if (strcmp(inbuffer, "QUIT") == 0)
                {
                    // 移除观察者
                    _removeuser(cli);
                    message = cli.Addr() + "# " + "我走了，你们聊！";
                }
                else
                {
                    // 新增用户
                    _adduser(cli);
                    message = cli.Addr() + "# " + inbuffer;
                }
                // 新增用户
                _adduser(cli);
                // 构建转发任务,推送给线程池，让线程池进行转发
                task_t task = std::bind(UdpServer::_route, _sockfd, message);
                ThreadPool<task_t>::GetInstance()->Enqueue(task);

                std::string clientinfo = cli.Ip() + ":" + std::to_string(cli.Port()) + " # " + inbuffer;
                LOG(LogLevel::DEBUG) << clientinfo;
                std::string echo_string = "echo# ";
                echo_string += inbuffer;
                ::sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, CONV(&peer), sizeof(peer));
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if (_sockfd > gdefaultsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd;
    // uint16_t _port;// 服务器未来的端口号
    InetAddr _addr;
    // // std::string _ip;// 服务器对应的ip   云服务器不需要手动bind ip地址
    bool _isrunning; // 服务器运行状态

    // 新增用户
    adduser_t _adduser;
    //移除用户
    remove_t _removeuser;
    // 数据转发
    route_t _route;
};

#endif